package game.tileMap.model
{
	
	
	
	
	
	import com.greensock.TweenLite;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import game.tileMap.model.vo.Unit;
	
	import mx.events.DynamicEvent;
	
	
	

	public class BattleModel extends EventDispatcher{
		//public static const NAME:String = "BattleAppProxy";
		
		public static const SETUP_STATUSWINDOWS:String="setup_statuswindows";
		public static const START_PARTY_COMMAND:String="start_party_command";
		public static const START_ACTOR_COMMAND_SELECTION:String="start_actor_command_selection";
		public static const END_SKILL_SELECT:String = "end_skill_select";
		
		//主阶段，个角色行动设置完毕
		public static const START_MAIN:String="start_main";
		
		public static const CREAT_BATTLER_SPRITES:String="creat_battler_sprites";
		public static const PLAY_ANIMATION:String="play_animation";
		public static const DISPLAY_ACTION:String="display_action";
		public static const STATE_CHANGE:String="state_change";
		
		public static const WIN:String="win";
		public static const GAME_OVER:String="game_over";
		
		public var phase:int;
		public var actionBattlers:Array;
		public var turn:int;
		public var actorIndex:int;
		public var activeBattler:Battler;
		
		public var cpuTroop:Troop;
		public var party:Troop;
		private var battleFormula:BattleFormula;
		
		public var in_battle:Boolean
		public var map:GameMapModel;
		public function BattleModel(){
			
			trace("战斗MODEL初始化")
			this.map=GameMapModel.getInstance();
			init();
		}
		
	

		
		
		
		private function init():void{
			actionBattlers=[];
		
			battleFormula=new BattleFormula();
			
			
		}
		
		private function sendEvent(eventName:String,obj:Object=null):void{
			var event:Event;
			if (obj){
				var dyEvent:DynamicEvent=new DynamicEvent(eventName);
				
				dyEvent.obj=obj;
				event=dyEvent;
			}else{
				event=new Event(eventName);
			}
			
			dispatchEvent(event);
		}
		
		
		public function reset():void{
			cpuTroop=null;
			turn=0;
			actorIndex=0;
			in_battle=false;
	//		party.clear();
		}
		
		
		
		
		
		
		
		private function call_gameover():void{
			sendEvent(GAME_OVER);
			trace("游戏结束")
		}
		
		//战斗开始
		public function start():void{
			trace("战斗开始")
			in_battle=true;
			party=map.troops[0];
			cpuTroop=map.troops[1]
			process_battle_start()
			start_main();
		}
		
		
		private function  process_battle_event():void{
			if (judge_win_loss()){
				return;
			}
			//return if $game_temp.next_scene != nil
      		//$game_troop.interpreter.update
     		// $game_troop.setup_battle_event
     	// wait_for_message
    	 // process_action if $game_troop.forcing_battler != nil
    	//  return unless $game_troop.interpreter.running?
    	 //	 update_basic
		}
		
		
		/**
		 *判断胜负结果 
		 * @return 胜负已分
		 * 
		 */		
		private function judge_win_loss():Boolean{
			
			 return false
			
		      
		   
		}
    	
    	private function process_defeat():void{
//    		 @info_viewport.visible = false
//    @message_window.visible = true
//    text = sprintf(Vocab::Defeat, $game_party.name)
//    $game_message.texts.push(text)
//    wait_for_message
   			 battle_end(2)
    	}
   
   		private function process_victory():void{
//			display_exp_and_gold
//			display_drop_items
			deal_level_up();
			trace("胜利！！！！！！！！！！！！！！")
   			battle_end(0)
			sendEvent(WIN);
   		}
    
		/**
		 *处理升级 
		 * 
		 */		
		private function deal_level_up():void{
			var exp:int =1000
//			for each(var actor:Actor in party.existing_members){
//				//last_level = actor.level
//				//last_skills = actor.skills
//				actor.gain_exp(exp)
//			}
		}
    	//   result : 结果（0：胜利，1：逃跑，2：失败）
		private function battle_end(result:int):void{
		  	if (result == 2){
				trace("团队全灭！！！！！！！！！！！！！！！！！！！！！！")
		  		 call_gameover();
		  	}else{
		  	//	party.clear_actions();
		    //  party.remove_states_battle
		   //  cpuTroop.clear();
				
		  
		  	}
		     
		  
		    in_battle = false
		}
    
		
		
		
		
		//显示所获得的金钱和经验值
		private function display_exp_and_gold():void{
			
		}
		
		//显示所获得的掉落物品
  		private function display_drop_items():void{
  		
  		}
  		
  		//显示升级
  		private function display_level_up():void{
  		
  		}
		
		//战斗开始处理
		private function  process_battle_start():void{
			//清空消息
			//等待10
			//显示敌人出现消息
			 //生成逃跑机率make_escape_ratio
    			//战斗事件处理
			process_battle_event();
   				 start_party();
		}


		//开始下一轮队伍行动  
		private function  start_party():void{
    	  actorIndex = -1
     		activeBattler = null;
     		 //start_main();
			//sendEvent(START_PARTY_COMMAND);
		}
		
		
		
		
		
		
		
		
		

//===================================================================================		
		//开始执行战斗处理
		public function start_main():void{
			phase = 4
   			turn++;
    		actorIndex = -1
    		activeBattler = null;
    		trace("主阶段！生成敌人行动")
    		//cpuTroop.make_actions();
    		//party.make_actions();
    		makeActionOrders();
			
    		
			sendEvent(START_MAIN);
			process_action();
		}
		
		//排列行动顺序	
		private function makeActionOrders():void{
			actionBattlers=[];
			for (var i:int=0;i<map.troops.length;i++){
				var troop:Troop=map.troops[i];
				actionBattlers=actionBattlers.concat(troop.members);
				
			}
			for each(var battler:Battler in actionBattlers){
				battler.action.make_speed();
			}
			
			actionBattlers.sort(sortOnSpeed);
			for(var i:int = 0; i < actionBattlers.length; i++) {
				var index:Battler = actionBattlers[i];
			//	trace("速度排列：：："+index.battler_name, ": " + index.action.speed);
			}
		}
		
		private function sortOnSpeed(a:Battler, b:Battler):Number {
			var speed1:Number = a.action.speed;
			var speed2:Number = b.action.speed;
			
			if(speed1 > speed2) {
				return -1;
			} else if(speed1 < speed2) {
				return 1;
			} else  {
				return 0;
			}
		}
		
		
		/**
		 * 战斗行动处理,步进
		 * 
		 */	
		public function process_action():void{
			if (judge_win_loss()){
				return;
			}
			set_next_active_battler();
			if (activeBattler==null){
				turn_end();
				return;
			}
			//如果行动条件允许，执行行动
			
			execute_action();
			
		}
		
		
		/**
		 * 行动结束，状态自然恢复判定并开始下个角色行动
		 * 行动播放完后调用
		 * 
		 */		
		public function endAction(delay:int=0):void{
			if (delay>0){
				TweenLite.delayedCall(delay,process_action,[],true);
			}else{
				process_action();
			}
			
			
		}
		
		public function set_next_active_battler():void{
			 activeBattler = actionBattlers.shift();
			
		}
		
		
		public function remove_states_auto():Boolean{
			var last_st:Array = activeBattler.states
				activeBattler.remove_states_auto();
			if (activeBattler.states != last_st){
				
			//	display_state_changes(activeBattler)
			//	sendEvent(STATE_CHANGE);
				return true;
			}
			return false;
		}
		
		
		public function turn_end():void{
			//cpuTroop.turn_ending = true
		//    party.slip_damage_effect()
		//    cpuTroop.slip_damage_effect()
		//    party.do_auto_recovery()
		   // cpuTroop.preemptive = false
		   //cpuTroop.surprise = false
		//    process_battle_event();
		  //  cpuTroop.turn_ending = false
			map.startNewTurn();
		    
		}
		
		
		/**
		 * 执行行动，发送事件 播放动作动画完毕后再继续调用执行下个人的行动 
		 * 
		 */		
		public function execute_action():void{
			execute_action_attack();
			
			
			//便于扩展，发送dyEvent
			var evtObj:Object=new Object();
			sendEvent(BattleModel.DISPLAY_ACTION,evtObj);	
			
		}


//====================计算行动效果并发出相应消息给视图演示动画===============================================================		
		public function execute_action_attack():void{
			//trace(activeBattler.battler_name+"攻击")
			if (activeBattler.camp==0){
				var targets:Array = activeBattler.action.make_targets();
				
			}else{
				
			}
			
			for each(var target:Battler in targets){
			//	trace("计算攻击效果")
				battleFormula.attackEffect(activeBattler,target);
			}
//			var evtObj:Object=new Object();
//			evtObj.targets=targets;
//			evtObj.note=noteType
//			sendEvent(BattleModel.DISPLAY_ACTION,evtObj);	
		}
		
		
		
		
		public function execute_action_guard():void{
			
		}
		
		public function execute_action_wait():void{
			
		}
		
	
	}
}